package com.dd.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**\
 * 全局异常处理器
 */

@Slf4j
@ResponseBody   //需要返回JSON数据
//该注解表示加了RestController,Controller注解的类获取的请求都会被拦截
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    //异常处理方法，该注解表示该方法处理这个异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){

        String msg = ex.getMessage();

        //拦截重复错误
        log.info(ex.getMessage());
        //如Duplicate entry '1234' for key 'employee.idx_username'

        if(msg.contains("Duplicate entry")){
            String[] split = msg.split(" ");
            return R.error(split[2] + "重复错误");
        }

        return R.error("未知错误");
    }

    /**
     *自定义异常处理，返回异常时给定的数据
     * 在全局异常处理器中将异常消息返回给页面
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){

        log.info(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
